<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\ResponseData;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Http\Requests\Order\OrderRequest;
//用车中
class UsingController extends Controller
{
    public $days=0;
    public $hours = 0;
    use ResponseData,NewBaseData;
    public function list(Request $request){
        $size = $request->input('size',10);
        $data = CarOrder::query()
            ->with('user')
            ->where('openid',$request->openid)
            ->where('status',Constant::ORDER_CREATE)->paginate($size);
        return $this->success($data);
    }
    public function edit(OrderRequest $request){
        $data = CarOrder::query()
            ->where('openid',$request->openid)
            ->where('order_sn',$request->order_sn)
            ->where('status',Constant::ORDER_CREATE)
            ->first();
        return $this->success($data);
    }
    public function update(OrderRequest $request){
        $order = CarOrder::query()
            ->where('status',Constant::ORDER_CREATE)
            ->where('order_sn',$request->order_sn)->first();
        if($order){
            
            $usedorders = CarOrder::query()->where('gear_car_id', $order->gear_car_id)->where('status',5)->whereIn('process_status',[1,2])->count();
            if($request->filled('return')&&$request->filled('return_position')){
                $start = $order->pre_fetch_time;
                $end = now();
                $order->status = Constant::ORDER_CLOSED;
                $order->return_time = $end;//实际还车时间
                $days = $this->diffDays($start,$end);
                $hours = $this->lastHours($start,$end);
                if($days>0){
                    $order->lease_days = $days;
                }else{
                    $order->lease_days = 1;
                }
                $order->fetch_hours = $hours;
                $order->return_position = $request->return_position;
                $order->save();
                //释放车辆
                if($usedorders==0){
                    RecognizeDrivingLicense::query()
                    ->where('id',$order->gear_car_id)
                    ->update(['is_used'=>Constant::CAR_EMPTY]);
                }
            }
            return $this->success('更新成功');
        }else{
            return $this->failed('订单不存在',201);
        }
    }
}
